<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24" >
            <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input disabled v-model="model.code" placeholder="请输入编号" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="材料请购单明细" :key="refKeys[0]" :forceRender="true">
<!--        <a-row>-->
<!--          &lt;!&ndash; 新增 &ndash;&gt;-->
<!--          <a-col :span="24">-->
<!--            <a-button-->
<!--              type="primary"-->
<!--              icon="PlusCircleOutlined"-->
<!--              size="large"-->
<!--              @click="addMateriel">-->
<!--              新增-->
<!--            </a-button>-->
<!--          </a-col>-->
<!--        </a-row>-->
        <a-row>
          <a-col :span="24">
            <!-- 表格 -->
            <j-vxe-table
              keep-source
              :ref="refKeys[0]"
              :loading="bussMaterialApplicationDetailTable.loading"
              :columns="bussMaterialApplicationDetailTable.columns"
              :dataSource="bussMaterialApplicationDetailTable.dataSource"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="true"
              :toolbar="true"
              :toolbarConfig="{slot: ['prefix', 'suffix'], btn: ['clearSelection']}"
              class="bold-border"
              :clickSelectRow="true"
              rowSelectionType="radio"
            >
              <template    v-slot:toolbarSuffix>
                <a-button
                  type="primary"
                  icon="PlusCircleOutlined"
                  size="large"
                  @click="addMateriel">
                  新增
                </a-button>
              </template>
            </j-vxe-table>
<!--            <a-table bordered-->
<!--                     tableLayout='fixed'-->
<!--                     :ref="refKeys[0]"-->
<!--                     :data-source="bussMaterialApplicationDetailTable.dataSource"-->
<!--                     :loading="bussMaterialApplicationDetailTable.loading"-->
<!--                     :columns="bussMaterialApplicationDetailTable.columns"-->
<!--                     :rowKey="(record,index)=>{return index}"-->
<!--                     :pagination="false" >-->
<!--                        <template slot="num" slot-scope="text, record">-->
<!--                          <editable-cell :text="text" @change="onCellChange(record, 'num', $event)" ></editable-cell>-->
<!--                        </template>-->
<!--                        <template slot="arrivalDate" slot-scope="text, record">-->
<!--                          <editable-cell :text="text" @change="onCellChange(record, 'arrivalDate', $event)" ></editable-cell>-->
<!--                        </template>-->
<!--                        <template slot="useDesc" slot-scope="text, record">-->
<!--                          <editable-cell :text="text" @change="onCellChange(record, 'useDesc', $event)" ></editable-cell>-->
<!--                        </template>-->
<!--                        <template slot="operation" slot-scope="text, record">-->
<!--                          <a-popconfirm-->
<!--                            title="确认删除?"-->
<!--                            @confirm="() => onDelete(record)"-->
<!--                          >-->
<!--                            <a href="javascript:;">删除</a>-->
<!--                          </a-popconfirm>-->
<!--                          &lt;!&ndash; <a @click="handleEdit(record)">保存</a>&ndash;&gt;-->
<!--                        </template>-->
<!--            </a-table>-->
          </a-col>
        </a-row>
      </a-tab-pane>
    </a-tabs>
    <erp-goods-list-model ref="selectGoodsList"
                          category="4"
                          @goodsOk="goodsOk"
                          checkval='radio'>
    </erp-goods-list-model>
  </a-spin>
</template>

<script>
  import ErpGoodsListModel from "@comp/base/modal/ErpGoodsListModal";
  import { getAction, httpAction, postAction, putAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import EditableCell from '@comp/table/EditableCell'

  export default {
    name: 'BussMaterialApplicationForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
      ErpGoodsListModel,
      EditableCell
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
          code:'',
            details:[]
          },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
        },
        refKeys: ['bussMaterialApplicationDetail', ],
        tableKeys:['bussMaterialApplicationDetail', ],
        activeKey: 'bussMaterialApplicationDetail',
        // 材料请购单明细
        bussMaterialApplicationDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料编号',
              key: 'materialCode',
              type: JVXETypes.normal,
              width: '150px',
            },
            {
              title: '物料编号',
              key: 'materialName',
              type: JVXETypes.normal,
              width: '150px',
            },
            {
              title: '规格',
              key: 'spec',
              type: JVXETypes.normal,
              width: '150px',
            },
            {
              title: '单位',
              key: 'unit',
              type: JVXETypes.normal,
              width: '150px',
            },
            {
              title: '数量',
              key: 'num',
              type: JVXETypes.inputNumber,
              width: '150px',
            },
            {
              title: '到货日期',
              key: 'arrivalDate',
              type: JVXETypes.date,
              width: '150px',
            },
            {
              title: '用途',
              key: 'useDesc',
              type: JVXETypes.input,
              width: '150px',
            },
            {
              title: '操作',
              dataIndex: 'operation',
              scopedSlots: { customRender: 'operation' },
            },
          ]
        },
        url: {
          add: "/procurement/add",
          edit: "/procurement/edit",
          queryById: "/procurement/queryById",
          bussMaterialApplicationDetail: {
            list: '/procurement/detail'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    methods: {
      onCellChange(record, dataIndex, value) {
        this.$set(record, dataIndex,value)
      },
      onDelete(record){
        const dataSource = [...this.model.details];
        this.model.details = dataSource.filter(item => item !== record);
      },
      goodsOk(data){
        let detail = {};
        detail.materialName = data.name
        detail.materialCode = data.code
        detail.materialId = data.id
        detail.spec = data.noneSpec
        detail.unit = data.auUnit_dictText;
        this.bussMaterialApplicationDetailTable.dataSource.push(detail)
        // this.model.details.push(detail);
        console.log(this.model)
      },
      addMateriel(){
        this.$nextTick(()=>{
          this.$refs.selectGoodsList.add();
        })
      },
      addBefore(){
        this.bussMaterialApplicationDetailTable.dataSource=[]
        this.getSequenceNum()
      },
      getSequenceNum() {
        let url = "/sys/fillRule/executeRuleByCode/cgqgd";
        putAction(url, {}).then(res => {
          // 执行成功，获取返回的值，并赋到页面上
          if (res.success) {
            this.model.code = res.result;
          }
        })
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      edit(record) {
        if (typeof this.editBefore === 'function') this.editBefore(record)
        this.visible = true
        this.activeKey = this.refKeys[0]
        this.$refs.form.resetFields()
        this.model = Object.assign({}, record)
        // this.$set(this.model, "code", record.applicationCode)
        // console.log("id:",record.applicationId)
        // this.$set(this.model, "id", record.applicationId)
        // this.$set(this.model, "code", record.applicationCode)
        if (typeof this.editAfter === 'function') this.editAfter(this.model)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        // if(!this.model.details){
        //   // Object.assign(this.model, {details:[]});
        //   this.$set(this.model, "details", [])
        // }
        if ( this.model.id ) {
          let params = { id: this.model.id }
          // this.requestSubData(this.url.bussMaterialApplicationDetail.list, params, this.model,"details")
          this.requestSubTableData(this.url.bussMaterialApplicationDetail.list, params, this.bussMaterialApplicationDetailTable)
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          bussMaterialApplicationDetailList: allValues.tablesValue[0].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      submitForm() {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            httpAction(httpurl, this.model, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
    }
  }
</script>

<style scoped>
</style>